package controllers.admin;

import java.util.ArrayList;
import java.util.List;

import models.Administrator;
import models.Brand;
import models.PricedCommodity;
import models.QueryBean;
import models.BaseEntity.Status;
import models.rbac.Role;
import play.data.validation.Required;
import play.data.validation.Valid;
import play.mvc.Controller;
import play.mvc.With;
import controllers.GlobalVariables;
import controllers.Secure;
import controllers.ValidationUtil;

@With(Secure.class)
public class Administrators extends Controller {
	public static void index() {
		render();
	}
	
	public static void indexTable(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
			queryBean.isDesc = true;
		}
		StringBuilder hql = new StringBuilder("id != null and username != 'admin' ");
    	List<Object> objs = new ArrayList<Object>();
    	
    	if(!ValidationUtil.isEmpty(queryBean.keyword)) {
    		if(ValidationUtil.isLong(queryBean.keyword)) {
    			hql.append("and (id=? or ");
        		objs.add(Long.valueOf(queryBean.keyword));
    		} else {
    			hql.append("and (");
    		}
    		hql.append("username like ? or realname like ? or role.name like ?) ");
    		objs.add("%"+queryBean.keyword+"%");
    		objs.add("%"+queryBean.keyword+"%");
    		objs.add("%"+queryBean.keyword+"%");
    	}
    	
    	if(!ValidationUtil.isEmpty(queryBean.orderby)) {
    		hql.append(" order by " + queryBean.orderby);
    		if(queryBean.isDesc) 
    			hql.append(" desc ");
    		else
    			hql.append(" asc ");
    	} else {
    		hql.append(" order by createAt desc, lastModifiedAt desc ");
    	}
		
		//页数计算
		queryBean.totalQuantity = Administrator.count(hql.toString(), objs.toArray());
		queryBean.pageCaculate();
		
		List<Administrator> admins = Administrator.find(hql.toString(), objs.toArray()).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		
		render(admins, queryBean);
	}
	
	public static void newAdmin(Administrator admin) {
		if(admin == null) {
			admin = new Administrator();
		}
		
		List<Role> roles = Role.findAll();
		render(admin, roles);
	}
	
	public static void create(@Valid Administrator admin) {
		if(!ValidationUtil.isEmpty(admin.username)) {
			Administrator existadmin = Administrator.find("byUsername", admin.username).first();
			if(existadmin != null) {
				validation.addError("admin.username", "此用户名已存在");
			}
		}
		if(validation.hasErrors()) {
//			params.flash();
			validation.keep();
			
			if(admin.role != null) {
				long roleId = admin.role.id;
				admin.role = new Role();
				admin.role.id = roleId;
			}
//			admin.role = null;
			newAdmin(admin);
		}
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator loginadmin = Administrator.find("byUsername", username).first();
		
		admin.setCreator(loginadmin);
		admin.resetModifier(admin);
		admin.save();
		indexTable(null);
	}
	
	public static void edit(long id) {
		Administrator admin = Administrator.findById(id);
		List<Role> roles = Role.findAll();
		render(admin, roles);
	}
	
	public static void update(@Valid Administrator admin) {
		if(validation.hasErrors()) {
//			params.flash();
			validation.keep();
			List<Role> roles = Role.findAll();
			render("admin/administrators/edit.html", admin, roles);
		}
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator loginadmin = Administrator.find("byUsername", username).first();
		
		Administrator oriAdmin = Administrator.findById(admin.id);
		oriAdmin.resetModifier(loginadmin);
		oriAdmin.realname = admin.realname;
		oriAdmin.password = admin.password;
		oriAdmin.role = Role.findById(admin.role.id);
		oriAdmin.save();
		indexTable(null);
	}
	
	public static void updateStatus(long id, Status status) throws Exception {
		Administrator admin = Administrator.findById(id);
		if(admin == null) {
			throw new Exception("此管理员已被删除");
		} else {
			String username = session.get(GlobalVariables.SECURE_ADMINNAME);
			Administrator longinadmin = Administrator.find("byUsername", username).first();
			admin.status = status;
			admin.resetModifier(longinadmin);
			admin.save();
		}
	}
	
	public static void editPassword(String oldPassword, 
			String newPassword, String rePassword) {
		render(oldPassword, newPassword, rePassword);
	}
	
	public static void updatePassword(@Required String oldPassword, 
			@Required String newPassword, @Required String rePassword) {
		oldPassword = oldPassword.trim();
		newPassword = newPassword.trim();
		rePassword = rePassword.trim();
		
		validation.range("oldPassword", oldPassword.length(), 8, 20);
		validation.range("newPassword", newPassword.length(), 8, 20);
		validation.range("rePassword", rePassword.length(), 8, 20);
		
		if(validation.hasErrors()) {
			validation.keep();
			editPassword(oldPassword, newPassword, rePassword);
		}
		
		String username = session.get(GlobalVariables.SECURE_ADMINNAME);
		Administrator loginadmin = Administrator.find("byUsername", username).first();
		if(!loginadmin.password.equalsIgnoreCase(oldPassword)) {
			validation.addError("oldPassword", "旧密码不正确");
		}
		if(!newPassword.equalsIgnoreCase(rePassword)) {
			validation.addError("rePassword", "与新密码不匹配");
		}
		if(validation.hasErrors()) {
			validation.keep();
			editPassword(oldPassword, newPassword, rePassword);
		}
		
		loginadmin.password = newPassword;
		loginadmin.resetModifier(loginadmin);
		loginadmin.save();
		validation.keep();
		validation.addError("newPassword", "保存成功");
		editPassword(null, null, null);
	}
	
	public static void indexRole() {
		render();
	}
	
	public static void indexRoleTable(QueryBean queryBean) {
		if(queryBean == null) {
			queryBean = new QueryBean();
			queryBean.isDesc = true;
		}
		StringBuilder hql = new StringBuilder("id != null ");
    	List<Object> objs = new ArrayList<Object>();
    	
    	if(!ValidationUtil.isEmpty(queryBean.keyword)) {
    		if(ValidationUtil.isLong(queryBean.keyword)) {
    			hql.append("and (id=? or ");
        		objs.add(Long.valueOf(queryBean.keyword));
    		} else {
    			hql.append("and (");
    		}
    		hql.append("name like ? ) ");
    		objs.add("%"+queryBean.keyword+"%");
    	}
    	
    	if(!ValidationUtil.isEmpty(queryBean.orderby)) {
    		hql.append(" order by " + queryBean.orderby);
    		if(queryBean.isDesc) 
    			hql.append(" desc ");
    		else
    			hql.append(" asc ");
    	} else {
    		hql.append(" order by createAt desc, lastModifiedAt desc ");
    	}
		
		//页数计算
		queryBean.totalQuantity = Role.count(hql.toString(), objs.toArray());
		queryBean.pageCaculate();
		
		List<Role> roles = Role.find(hql.toString(), objs.toArray()).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		
		render(roles, queryBean);
	}
	
	public static void updateRoleStatus(long id, Status status) throws Exception {
		Role role = Role.findById(id);
		if(role == null) {
			throw new Exception("此管理员已被删除");
		} else {
			String username = session.get(GlobalVariables.SECURE_ADMINNAME);
			Administrator longinadmin = Administrator.find("byUsername", username).first();
			role.status = status;
			role.resetModifier(longinadmin);
			role.save();
		}
	}
}